package com.processmining.filter;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.processmining.cache.RedisClient;
import com.processmining.dao.UserMapper;
import com.processmining.entity.User;
import com.processmining.util.exception.NoAuthorityException;

public class AuthFilter2 implements HandlerInterceptor{
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private RedisClient cli;
	private static final String[] MANAGER_URI = { "/manager"};

	private static final String[] USER_URI = {"user","rawLog","normLog","eventLog","mergeLog","logMining","listAllMEL","search","algoConfig","merge"};
	private static final String[] IGNORE_URI={"index.html","checkcode","login","register","activate","emailValid","static","emailValid","logoff"};

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object obj) throws Exception {
		HttpSession session=req.getSession();
		User u=(User) session.getAttribute("user");
		
		
		String url=req.getRequestURL().toString();
        /*Enumeration e=req.getAttributeNames();
        while(e.hasMoreElements()){
        	System.out.print((String)e.nextElement());
        }*/
		System.out.print(url);
		for(String s:IGNORE_URI){
			if(url.contains(s)){
				return true;
			}
		}
		if(u==null){
			throw new NoAuthorityException("Not Login");
		}
		
		int uid=u.getId();
		User user=userMapper.selectByPrimaryKey(uid);
		
		if(user==null||user.getBanned()){
			throw new NoAuthorityException("Not Login");
		}
		cli.setex(String.valueOf(uid),20*60,String.valueOf(0));
		
		int type=user.getType();
		
		
		for(String s:MANAGER_URI){
			if(url.contains(s)&&type==1){
				return true;
			}
		}
		
		for(String s:USER_URI){
			if(url.contains(s)&&type==0){
				return true;
			}
		}
		
		throw new Exception("No authority");
	}

}
